// BackToTop.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useBackToTop(parentContainer: any) {
  const isVisible = ref(false);
  const scrollTop = ref(0);

  // 监听滚动事件
  const handleScroll = () => {
    if (!parentContainer.value) return;
    const scrollY = parentContainer.value.scrollTop;
    scrollTop.value = scrollY;
    isVisible.value = scrollY > 100; // 当滚动超过 300px 时显示按钮
  };

  // 滚动到父容器顶部
  const scrollToTop = () => {
    if (!parentContainer.value) return;
    parentContainer.value.scrollTop = 0;
  };

  // 监听容器滚动和调整大小
  onMounted(() => {
    if (parentContainer.value) {
      parentContainer.value.addEventListener('scroll', handleScroll);
      parentContainer.value.addEventListener('resize', handleScroll);
    }
  });

  onUnmounted(() => {
    if (parentContainer.value) {
      parentContainer.value.removeEventListener('scroll', handleScroll);
      parentContainer.value.removeEventListener('resize', handleScroll);
    }
  });

  return { isVisible, scrollToTop };
}